package com.kaiwukj.android.ufamily.mvp.ui.page.service.gm;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseActivity;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.mvp.http.entity.helper.GMDeviceInfo;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.GMOrderDetailResult;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.kaiwukj.android.ufamily.utils.ScreenOrientationHelper;
import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import com.videogo.realplay.RealPlayStatus;
import com.videogo.widget.CheckTextButton;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterUrlKt.OrderGMVideoUrl)
public class GMOrderVideoActivity extends BaseActivity implements Handler.Callback {


    // UI消息
    public static final int MSG_PLAY_UI_UPDATE = 200;

    public static final int MSG_AUTO_START_PLAY = 202;

    public static final int MSG_CLOSE_PTZ_PROMPT = 203;

    public static final int MSG_HIDE_PTZ_DIRECTION = 204;

    public static final int MSG_HIDE_PAGE_ANIM = 205;

    public static final int MSG_PLAY_UI_REFRESH = 206;

    public static final int MSG_PREVIEW_START_PLAY = 207;

    public static final int MSG_SET_VEDIOMODE_SUCCESS = 105;

    public static final int MSG_SET_VEDIOMODE_FAIL = 106;


    @BindView(R.id.container_header)
    ViewGroup containerHeader;
    @BindView(R.id.tv_title)
    TextView tvTitle;
   /* @BindView(R.id.refresh_layout)
    RefreshLayout refreshLayout;*/

    @BindView(R.id.container_video)
    ViewGroup containerVideo;
    @BindView(R.id.container_video_loading)
    ViewGroup containerVideoLoading;
    @BindView(R.id.view_video)
    SurfaceView mVideoView;
    @BindView(R.id.iv_video_full)
    View ivVideoFull;
    @BindView(R.id.rv_video_pos)
    RecyclerView rvVideoPos;
    @BindView(R.id.view_controller_left)
    View viewControllerLeft;
    @BindView(R.id.view_controller_up)
    View viewControllerUp;
    @BindView(R.id.view_controller_right)
    View viewControllerRight;
    @BindView(R.id.view_controller_down)
    View viewControllerDown;
    @BindView(R.id.tv_controller_voice)
    View tvControllerVoice;

    @Autowired
    GMOrderDetailResult result;


    private Handler mHandler;
    private EZPlayer mEZPlayer;
    private GMDeviceInfo deviceInfo = new GMDeviceInfo();
    private int mStatus = RealPlayStatus.STATUS_INIT;
    private SurfaceHolder mRealHolder;
    private ScreenOrientationHelper mScreenOrientationHelper;
    private int mOrientation = Configuration.ORIENTATION_PORTRAIT;
    private int mForceOrientation = 0;

    private boolean isBreakSound = false;//是否静音

    @OnClick(R.id.container_left)
    void onBackClick() {
        onBackPressedSupport();
       /* ARouter.getInstance().build(ARouterUrlKt.OrderGMDetailUrl)
                .withSerializable("orderResult", orderResult)
                .navigation();*/
    }


    @OnClick({R.id.tv_controller_quite, R.id.tv_controller_sc, R.id.tv_controller_back_video})
    void onVideoController(View view) {
        switch (view.getId()) {
            case R.id.tv_controller_quite:
                changedSound();
                break;
            case R.id.tv_controller_sc:
                cutPic();
                break;
            case R.id.tv_controller_back_video:
                ARouter.getInstance().build(ARouterUrlKt.GMVideoPlayBackList)
                        .withSerializable("deviceInfo", deviceInfo)
                        .navigation();
                break;
        }
    }


    @SuppressLint("ClickableViewAccessibility")
    private View.OnTouchListener mOnControllerTouchListener = (view, event) -> {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                switch (view.getId()) {
                    case R.id.view_controller_left:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTART);
                        break;
                    case R.id.view_controller_up:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTART);
                        break;
                    case R.id.view_controller_right:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTART);
                        break;
                    case R.id.view_controller_down:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTART);
                        break;
                    case R.id.tv_controller_voice:
                        if (mEZPlayer != null) {
                            mEZPlayer.startVoiceTalk();
                        }
                        break;
                }
                break;
            case MotionEvent.ACTION_UP:
                switch (view.getId()) {
                    case R.id.view_controller_left:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandLeft, EZConstants.EZPTZAction.EZPTZActionSTOP);
                        break;
                    case R.id.view_controller_up:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandUp, EZConstants.EZPTZAction.EZPTZActionSTOP);
                        break;
                    case R.id.view_controller_right:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandRight, EZConstants.EZPTZAction.EZPTZActionSTOP);
                        break;
                    case R.id.view_controller_down:
                        ptzOption(EZConstants.EZPTZCommand.EZPTZCommandDown, EZConstants.EZPTZAction.EZPTZActionSTOP);
                        break;
                    case R.id.tv_controller_voice:
                        if (mEZPlayer != null) {
                            mEZPlayer.stopVoiceTalk();
                        }
                        break;
                }
                break;
        }
        return true;
    };

    @Override
    protected int getLayoutId() {
        ARouter.getInstance().inject(this);
        return R.layout.activity_gm_order_video;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvTitle.setText("装修直播");
        viewControllerLeft.setOnTouchListener(mOnControllerTouchListener);
        viewControllerUp.setOnTouchListener(mOnControllerTouchListener);
        viewControllerRight.setOnTouchListener(mOnControllerTouchListener);
        viewControllerDown.setOnTouchListener(mOnControllerTouchListener);
        tvControllerVoice.setOnTouchListener(mOnControllerTouchListener);
        // refreshLayout.setEnableRefresh(false);
        mHandler = new Handler(this);
        //EZOpenSDK.getInstance().setAccessToken("at.1tn6tmc81mycaapfbtgpole06ztmr4ye-2h6ld1w42m-05pjnvk-p8bzm4nsz");
        mScreenOrientationHelper = new ScreenOrientationHelper(this, (CheckTextButton) ivVideoFull);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mStatus == RealPlayStatus.STATUS_PAUSE
                || mStatus == RealPlayStatus.STATUS_DECRYPT) {
            // 开始播放
            startRealPlay();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mScreenOrientationHelper != null) {
            mScreenOrientationHelper.postOnStop();
        }
        if (mStatus != RealPlayStatus.STATUS_STOP) {

            stopRealPlay();
            mStatus = RealPlayStatus.STATUS_PAUSE;
            //setRealPlayStopUI();
        } else {
            setLoadingStop();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mEZPlayer != null) {
            mEZPlayer.release();
        }
        if (mRealHolder != null) {
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        // mPresenter.fetchGMOrderDetail(orderId);
        if (result != null) {
            initUI(result);
        } else {
            showMessage("视频异常!");
            onBackPressedSupport();
        }
    }


    private void initUI(GMOrderDetailResult result) {
        initVideo(result.getDeviceVOList());
    }

    private void initVideo(List<GMOrderDetailResult.VOResult> voResult) {
        if (voResult == null || voResult.size() == 0) {
            containerVideo.setVisibility(View.GONE);
            return;
        }

        rvVideoPos.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        if (rvVideoPos.getItemDecorationCount() == 0) {
            rvVideoPos.addItemDecoration(new SpaceItemDecoration(10, RecyclerView.HORIZONTAL));
        }
        GMOrderDetailVideoIndexAdapter videoIndexAdapter = new GMOrderDetailVideoIndexAdapter(voResult);
        rvVideoPos.setAdapter(videoIndexAdapter);
        // videoIndexAdapter.checkItem(0);

        videoIndexAdapter.setOnCheckChangedListener(position -> {
            GMOrderDetailResult.VOResult item = videoIndexAdapter.getItem(position);
            EZOpenSDK.getInstance().setAccessToken(item.getAccessToken());
            initVideo(item.getEquipmentSerialNumber(), item.getVerificationCode(), mRealHolder);
        });
        mRealHolder = mVideoView.getHolder();
        mRealHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (mEZPlayer != null) mEZPlayer.setSurfaceHold(holder);
                mRealHolder = holder;
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mEZPlayer != null) {
                    mEZPlayer.setSurfaceHold(holder);
                }
                mRealHolder = holder;
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (mEZPlayer != null) mEZPlayer.setSurfaceHold(null);
                mRealHolder = null;
            }
        });

        if (videoIndexAdapter.getItemCount() > 0) {
            videoIndexAdapter.checkItem(0);
        }


    }


    private void initVideo(String deviceSerial, String verifyCode, SurfaceHolder surfaceHolder) {
        if (mEZPlayer != null) {
            releasePlayer();
        }
        deviceInfo.setCameraNo(1);
        deviceInfo.setDeviceSerial(deviceSerial);
        deviceInfo.setVerifyCode(verifyCode);
        mEZPlayer = EZOpenSDK.getInstance().createPlayer(deviceSerial, deviceInfo.getCameraNo());
        if (mEZPlayer == null) {
            showMessage("获取摄像头失败");
            return;
        }

        //设置Handler, 该handler将被用于从播放器向handler传递消息
        mEZPlayer.setHandler(mHandler);

        //设置播放器的显示Surface
        mEZPlayer.setSurfaceHold(surfaceHolder);

        /**
         * 设备加密的需要传入密码
         * 传入视频加密密码，用于加密视频的解码，该接口可以在收到ERROR_INNER_VERIFYCODE_NEED或ERROR_INNER_VERIFYCODE_ERROR错误回调时调用
         * @param verifyCode 视频加密密码，默认为设备的6位验证码
         */
        mEZPlayer.setPlayVerifyCode(verifyCode);
        //  mEZPlayer.openSound();

        startRealPlay();
        //停止直播
        // player.stopRealPlay();

        //释放资源
        //player.release();
    }

    private void startRealPlay() {
        if (mEZPlayer == null) {
            return;
        }

        if (mStatus == RealPlayStatus.STATUS_START || mStatus == RealPlayStatus.STATUS_PLAY) {
            return;
        }
        //开启直播
        mEZPlayer.startRealPlay();

        setLoadingStart();
        mStatus = RealPlayStatus.STATUS_START;
    }

    private void stopRealPlay() {
        if (mEZPlayer != null) {
            mEZPlayer.stopRealPlay();
            mStatus = RealPlayStatus.STATUS_STOP;
        }
    }

    private void releasePlayer() {
        if (mEZPlayer != null) {
            mEZPlayer.stopRealPlay();
            mEZPlayer.release();
        }
    }


    private void ptzOption(final EZConstants.EZPTZCommand command, final EZConstants.EZPTZAction action) {
        new Thread(() -> {
            boolean ptz_result = false;
            try {
                ptz_result = EZOpenSDK.getInstance().controlPTZ(deviceInfo.getDeviceSerial(), 1, command,
                        action, EZConstants.PTZ_SPEED_DEFAULT);
            } catch (BaseException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    public void onBackPressedSupport() {
        if (this.getResources().getConfiguration().orientation != Configuration.ORIENTATION_PORTRAIT) {
            mScreenOrientationHelper.portrait();
            return;
        }
        super.onBackPressedSupport();
    }


    private void setLoadingStop() {
        if (containerVideoLoading != null) {
            containerVideoLoading.setVisibility(View.GONE);
        }
    }

    private void setLoadingStart() {
        containerVideoLoading.setVisibility(View.VISIBLE);
        mScreenOrientationHelper.enableSensorOrientation();
    }

    private void setRealPlaySuccessUI() {
        mStatus = RealPlayStatus.STATUS_PLAY;
        setLoadingStop();
        if (mEZPlayer != null) {
            if (isBreakSound) {
                mEZPlayer.closeSound();
            } else {
                mEZPlayer.openSound();
            }
        }
        updateOrientation();
    }

    private void setRealPlayStopUI() {
        mStatus = RealPlayStatus.STATUS_PLAY;
        setLoadingStop();
        updateOrientation();
    }

    private void setRealPlayFailUI() {
        mStatus = RealPlayStatus.STATUS_PLAY;
        setLoadingStop();
        updateOrientation();
    }

    private void changedSound() {
        if (mEZPlayer != null) {
            if (!isBreakSound) {
                mEZPlayer.closeSound();
                isBreakSound = true;
            } else {
                mEZPlayer.openSound();
                isBreakSound = false;
            }
        }
    }

    private void cutPic() {
        if (mEZPlayer != null) {
            // String fileName = System.currentTimeMillis() + ".jpg";
            // String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
            // String filePath = path + File.separator + "ufamily" + File.separator + fileName;
            Bitmap bitmap = mEZPlayer.capturePicture();

            File file = ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.JPEG, 75);
            if (file != null && file.exists()) {
                showMessage("文件已保存到相册");
            }
            /*if (resultCode != -1) {
                showMessage("文件保存在:" + filePath);
                File file =
                        MediaStore.Images.Media.insertImage(getContentResolver(), BitmapFactory.decodeFile(file.getAbsolutePath()), file.getName(), null);
                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(file);
                intent.setData(uri);
                sendBroadcast(intent);
            }*/
        }
    }

    private void fullScreen(boolean enable) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        if (enable) {
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            lp.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(lp);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        mOrientation = newConfig.orientation;

        onOrientationChanged();
        super.onConfigurationChanged(newConfig);
    }

    private void onOrientationChanged() {
        if (mEZPlayer != null) updateOperatorUI();
    }

    private void updateOperatorUI() {
        if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
            fullScreen(false);
            updateOrientation();
            containerHeader.setVisibility(View.VISIBLE);
            rvVideoPos.setVisibility(View.VISIBLE);
            //containerContent.setVisibility(View.VISIBLE);
        } else {
            fullScreen(true);
            containerHeader.setVisibility(View.GONE);
            rvVideoPos.setVisibility(View.GONE);
            //containerContent.setVisibility(View.GONE);
        }
    }

    private void updateOrientation() {
        if (mStatus == RealPlayStatus.STATUS_PLAY) {
            setOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        } else {
            if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
                setOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } else {
                setOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            }
        }
    }

    private void setOrientation(int sensor) {
        if (mForceOrientation != 0) {
            //  LogUtil.d(TAG, "setOrientation mForceOrientation:" + mForceOrientation);
            return;
        }

        if (sensor == ActivityInfo.SCREEN_ORIENTATION_SENSOR)
            mScreenOrientationHelper.enableSensorOrientation();
        else
            mScreenOrientationHelper.disableSensorOrientation();
    }

    public void setForceOrientation(int orientation) {
        if (mForceOrientation == orientation) {
            // LogUtil.d(TAG, "setForceOrientation no change");
            return;
        }
        mForceOrientation = orientation;
        if (mForceOrientation != 0) {
            if (mForceOrientation != mOrientation) {
                if (mForceOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                    mScreenOrientationHelper.portrait();
                } else {
                    mScreenOrientationHelper.landscape();
                }
            }
            mScreenOrientationHelper.disableSensorOrientation();
        } else {
            updateOrientation();
        }
    }

    @Override
    public boolean handleMessage(@NonNull Message msg) {
        if (this.isFinishing()) {
            return false;
        }
        switch (msg.what) {
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                setRealPlaySuccessUI();
                break;
            case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                handlePlayFail(msg.obj);
                break;
            case MSG_AUTO_START_PLAY:
                startRealPlay();
                break;
            case MSG_PREVIEW_START_PLAY:
                mStatus = RealPlayStatus.STATUS_INIT;
                startRealPlay();
                break;
        }
        return false;
    }

    private void handlePlayFail(Object obj) {
        int errorCode = 0;
        if (obj != null) {
            ErrorInfo errorInfo = (ErrorInfo) obj;
            errorCode = errorInfo.errorCode;
            LogUtils.e("error------------------------->" + GsonUtils.toJson(errorInfo));
        }


        stopRealPlay();

        updateRealPlayFailUI(errorCode);
    }

    private void updateRealPlayFailUI(int errorCode) {
        String txt = "";
        // 判断返回的错误码
        switch (errorCode) {
            case ErrorCode.ERROR_TRANSF_ACCESSTOKEN_ERROR:
                txt = "萤石token无效";
                return;
            case ErrorCode.ERROR_CAS_MSG_PU_NO_RESOURCE:
                txt = "设备连接数过大，停止其他连接后再试试吧";
                break;
            case ErrorCode.ERROR_TRANSF_DEVICE_OFFLINE:
                txt = "设备不在线";
                break;
            case ErrorCode.ERROR_INNER_STREAM_TIMEOUT:
                txt = "播放失败，连接设备异常";
                break;
            case ErrorCode.ERROR_WEB_CODE_ERROR:
                //VerifySmsCodeUtil.openSmsVerifyDialog(Constant.SMS_VERIFY_LOGIN, this, this);
                //txt = Utils.getErrorTip(this, R.string.check_feature_code_fail, errorCode);
                txt = "验证硬件特征码失败";
                break;
            case ErrorCode.ERROR_WEB_HARDWARE_SIGNATURE_OP_ERROR:
                //VerifySmsCodeUtil.openSmsVerifyDialog(Constant.SMS_VERIFY_HARDWARE, this, null);
//                SecureValidate.secureValidateDialog(this, this);
                //txt = Utils.getErrorTip(this, R.string.check_feature_code_fail, errorCode);
                txt = "验证硬件特征码失败!";
                break;
            case ErrorCode.ERROR_TRANSF_TERMINAL_BINDING:
                txt = "请在萤石客户端关闭终端绑定 "
                        + "Please close the terminal binding on the fluorite client";
                break;
            // 收到这两个错误码，可以弹出对话框，让用户输入密码后，重新取流预览
            case ErrorCode.ERROR_INNER_VERIFYCODE_NEED:
            case ErrorCode.ERROR_INNER_VERIFYCODE_ERROR: {
                /*DataManager.getInstance().setDeviceSerialVerifyCode(mCameraInfo.getDeviceSerial(), null);
                VerifyCodeInput.VerifyCodeInputDialog(this, this).show();*/
                txt = "验证错误";
            }
            break;
            case ErrorCode.ERROR_EXTRA_SQUARE_NO_SHARING:
            default:
                txt = "视频播放失败";
                break;
        }

        showMessage(txt);

        setRealPlayStopUI();
    }

}
